// com/zbo/servlet/WeekConfigServlet.java
package com.zbo.servlet;

import com.alibaba.fastjson2.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;

@WebServlet("/week-config")
public class WeekConfigServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        try {
            HttpSession session = req.getSession();
            Integer studentId = (Integer) session.getAttribute("studentId");
            if (studentId == null) {
                sendJson(out, false, "未登录");
                return;
            }

            int currentTeachingWeek = Integer.parseInt(req.getParameter("week"));
            if (currentTeachingWeek < 1 || currentTeachingWeek > 18) {
                sendJson(out, false, "周数必须为1-18");
                return;
            }

            // 获取今天日期
            LocalDate today = LocalDate.now();

            // 存入 Session：基准日期 + 基准周
            session.setAttribute("baseDate", today.toString());
            session.setAttribute("baseWeek", currentTeachingWeek);

            sendJson(out, true, "当前周设置成功");

        } catch (Exception e) {
            e.printStackTrace();
            sendJson(out, false, "设置失败: " + e.getMessage());
        } finally {
            out.flush();
        }
    }

    private void sendJson(PrintWriter out, boolean success, String message) {
        JSONObject res = new JSONObject();
        res.put("success", success);
        res.put("message", message);
        out.print(res.toJSONString());
    }
}